<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2023-09-18 11:34:11
 * @LastEditors: 甯左龙 1173405584@qq.com
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\form\uiButton\uiButton.vue
 * CIMC-V2
-->
<template>
  <div class="ui-button flex mr-1 mt-0" :class="{ hidden: conditionProperty.hidden || info.extension.hidden.value }">
    <el-button
      :id="domId"
      :ref="info._id"
      v-ui-ref="vSetRef"
      :circle="info.extension.circle.value"
      :disabled="conditionProperty.disabled || info.extension.disabled.value"
      :plain="info.extension.plain.value"
      :round="info.extension.round.value"
      :size="info.extension.size.value"
      :style="{
        paddingTop: info.extension.paddingTop ? info.extension.paddingTop.value : '2px',
        paddingRight: info.extension.paddingRight ? info.extension.paddingRight.value : '10px',
        paddingBottom: info.extension.paddingBottom ? info.extension.paddingBottom.value : '2px',
        paddingLeft: info.extension.paddingLeft ? info.extension.paddingLeft.value : '10px',
        color: info.extension.textColor && info.extension.textColor.value,
        cursor: onClickIsRunning ? 'not-allowed' : '',
      }"
      :loading="onClickIsRunning"
      :type="info.extension.type.value"
      @click="onClick"
      @keyup.enter="$handleEnter"
    >
      <vui-icon
        v-if="info.extension.icon.value"
        :icon="info.extension.icon.value"
        :style="{ marginRight: info.extension.circle.value ? '' : '5px' }"
      />
      <template v-if="!info.extension.circle.value">
        {{ info.extension.value.value }}
        <template v-if="getKeyboardShortcut && getKeyboardShortcut.length > 0">
          <span class="text-s">({{ getKeyboardShortcut[0].text }})</span>
        </template>
      </template>
    </el-button>
  </div>
</template>
<script>
  import { defineComponent } from 'vue'
  import { UiMixin, RefsInjectMixin, ConditionMixin } from '@ve/mixin'
  import { getModelByModelTree } from '@ve/utils/utils'
  import { customAlphabet } from 'nanoid'
  import { CODE_CONTROL } from '@/utils/keyInputCode'

  export default defineComponent({
    name: 'UiButton',
    components: {},
    mixins: [UiMixin, RefsInjectMixin, ConditionMixin],
    data() {
      return {
        autofocus: false,
        domId: '',
        onClickIsRunning: false,
      }
    },
    computed: {
      //获取选择模块信息
      getKeyboardShortcut() {
        return this.info.extension?.keyboardShortcut?.value
      },
    },
    created() {
      this.domId = `${this.componentId()}_${this.info._id}`
    },
    mounted() {
      let doing = false
      addEventListener(
        'compositionstart',
        () => {
          // console.log('按下-1')
          doing = true
        },
        false
      )
      addEventListener(
        'keyup',
        (e) => {
          if (!doing) {
            // console.log('按下-2')
            this.keyDown(e)
          }
        },
        false
      ) //创建监听键盘事件
      addEventListener(
        'compositionend',
        (e) => {
          // console.log('按下-3')
          doing = false
          this.keyDown(e)
        },
        false
      )
    },
    unmounted() {
      removeEventListener('keydown', this.keyDown)
    },
    methods: {
      componentId() {
        const nanoid = customAlphabet('abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMN', 6)
        return nanoid()
      },
      keyDown(e) {
        if (!this.hasPreview) {
          // console.log('预览模式不运行 keyDown')
          return
        }
        const { altKey, ctrlKey, shiftKey, key } = e
        // console.log('demo', altKey, ctrlKey, shiftKey, key, code)
        // console.log('demo1',this.info.name,this.info.extension.keyboardShortcut)
        if (this.info.extension.keyboardShortcut) {
          if (!CODE_CONTROL.includes(key)) {
            // if (!this.keyRange.includes(code)) return
            let controlKey = ''
            ;[
              { key: altKey, text: 'Alt' },
              { key: ctrlKey, text: 'Ctrl' },
              { key: shiftKey, text: 'Shift' },
            ].forEach((curKey) => {
              if (curKey.key) {
                if (controlKey) controlKey += '+'
                controlKey += curKey.text
              }
            })
            if (key) {
              if (controlKey) controlKey += '+'
              controlKey += key.toUpperCase()
            }
            if (this.info.extension.keyboardShortcut.value.length < 0) {
              return false
            }
            // console.log('this.info.extension.keyboardShortcut.value', this.info.extension.keyboardShortcut.value)
            if (this.info.extension.keyboardShortcut?.value[0]?.text == controlKey) {
              this.onClick()
              e.preventDefault() //阻止浏览器默认事件
              return false
            }
          }
        }
      },
      // $handleEnter() {
      //   // 回车事件
      //   console.log('点击了回车！！！')
      //   // 如果有配置回车选中 则选中组件
      //   const selectedModuleId = this.info.extension.enterSelect && this.info.extension.enterSelect.value[0]
      //   if (!selectedModuleId) return
      //   const moduleRef = this.vuiComponents[selectedModuleId] && this.vuiComponents[selectedModuleId].ref
      //   if (moduleRef && moduleRef.focus) {
      //     moduleRef.focus()
      //   }
      //   if (moduleRef && moduleRef.select) {
      //     moduleRef.select()
      //   }
      // },
      $handleEnter() {
        // 回车事件
        // console.log('点击了回车！！！', this.$refs)
        // 使当前组件失焦
        let currentModuleRef = this.vuiComponents[this.info._id] && this.vuiComponents[this.info._id].ref
        currentModuleRef && currentModuleRef.blur && currentModuleRef.blur()
        // 触发回车事件
        this.onEnterKeyUp &&
          this.onEnterKeyUp((_this) => {
            // 将回车选中下一个组件放在回车事件之后 以方便控制动作中接口报错不聚焦下一个组件
            // 如果有配置回车选中 则选中组件
            let selectedModuleId = _this.info.extension.enterSelect && _this.info.extension.enterSelect.value[0]
            if (_this.info._id.indexOf('UiDynamicFormLOT') > -1) {
              // 如果当前事件是由批次属性内部组件触发则聚焦到下一个组件
              const currentIndex = _this.info.CUR_LOT_list.indexOf(_this.info._id)
              if (currentIndex === -1) return
              if (currentIndex < _this.info.CUR_LOT_list.length - 1) {
                // 如果当前组件已经是批次属性组件内的最后一个可聚焦组件 则聚焦到配置的外部组件
                selectedModuleId = _this.info.CUR_LOT_list[currentIndex + 1]
              } else {
                // 如果当前是批次属性里面的最后一个组件触发的回车点击 则触发批次属性组件的回车事件
                const parentId = _this.info.parentId
                this.dynamicFormEnterKeyUp(parentId)
                return
              }
            } else if (selectedModuleId && selectedModuleId.indexOf('uiDynamicFormLot') > -1) {
              // 如果选择的是批次属性组件 则进入批次属性组件内部
              const moduleTree = _this.$store.state.preview.pages[_this.$store.state.preview.nowPageId]
              const lotModule = getModelByModelTree(selectedModuleId, moduleTree)
              if (lotModule.CUR_LOT_list && lotModule.CUR_LOT_list.length) {
                // 如果批次属性组件有配置光标停留组件，则聚焦第一个组件
                selectedModuleId = lotModule.CUR_LOT_list[0]
              }
            }
            if (!selectedModuleId) return
            if (selectedModuleId.indexOf('uiSelectLayerNew') > -1 || selectedModuleId.indexOf('uiButton') > -1) {
              // 如果下一个组件是三点选择组件 或者按钮组件 则单独触发组件的回车选中方法
              const moduleSelf = _this.vuiComponents[selectedModuleId] && _this.vuiComponents[selectedModuleId].self
              moduleSelf && moduleSelf.enterFocus()
            } else {
              const moduleRef = _this.vuiComponents[selectedModuleId] && _this.vuiComponents[selectedModuleId].ref
              if (moduleRef && moduleRef.focus) {
                moduleRef.focus()
              }
              if (moduleRef && moduleRef.select) {
                moduleRef.select()
              }
              if (_this.info.type === 'uiSelect') {
                // 如果是下拉选择组件 则使下拉组件失去焦点 并隐藏选择框
                const selfModuleRef = _this.vuiComponents[_this.info._id] && _this.vuiComponents[_this.info._id].ref
                selfModuleRef.blur()
              }
            }
          })
      },
      enterFocus() {
        console.log('触发了回车聚焦')
        // console.log(document.getElementById(this.domId))
        const buttonDom = document.getElementById(this.domId)
        buttonDom && buttonDom.focus()
        // this.autofocus = true
        // this.aaa = false
        // setTimeout(() => {
        //   console.log('显示按钮！！')
        //   this.aaa = true
        // })
        // this.$forceUpdate()
      },
    },
  })
</script>
<style scoped>
  /* .ui-button { */
  /* padding-top: 3px; */
  /* } */
</style>
